import datetime
import json
import logging

from base.connection import mongodb_util
from base.request import ApiBaseHandler
from common.definition import ret_msg

logger = logging.getLogger("wechat.handlers.log")


class Logger(ApiBaseHandler):
    async def post(self):
        """
        POST请求JSON示例:
        {
            "level": "error",
            "msg": "TEST ONLY!",
            "source": "log.py:17",
            "sourceURL": "https://wx.style999.com/static/app/index.html"
        }

        返回示例(code=0表示成功，code=-1表示失败并返回错误提示)
        {
            "code": 0,
            "data": "",
            "msg": "请求成功"
        }
        """
        log = json.loads(self.request.body.decode("utf-8"))
        log["created"] = str(datetime.datetime.now())
        level = log["level"]
        log_str = json.dumps(log)
        if level == "warning":
            logger.warning(log_str)
        elif level == "error":
            logger.error(log_str)
        elif level == "debug":
            logger.debug(log_str)
        elif level == "exception":
            logger.exception(log_str)
        else:
            logger.info(log_str)
        try:
            db = mongodb_util.db
            db.log.insert(log)
        except Exception as e:
            logger.error(e)
            return self.write(ret_msg(code=-1, error_message="日志录入失败, 请稍后重试!"))
        return self.write(ret_msg())
